#include "MultiJitteredSampler.h"

void MultiJitteredSampler::generateSamples() {
	// num_samples needs to be a perfect square
	int n = int(sqrt(numSamples));
	Double subcell_width = 1.0 / numSamples;

	// fill the samples array with dummy points to allow us to use the [] notation when we set the 
	// initial patterns
	samples.resize(numSets * numSamples, Vector2());

	// distribute points in the initial patterns
	for (int p = 0; p < numSets; p++)
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++) {
				samples[i * n + j + p * numSamples].x = (i * n + j) * subcell_width + subcell_width * RAND;
				samples[i * n + j + p * numSamples].y = (j * n + i) * subcell_width + subcell_width * RAND;
			}

	// shuffle x coordinates

	for (int p = 0; p < numSets; p++)
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++) {
				int k = RANDINTIN(j, n - 1);
				SWAP(samples[i * n + j + p * numSamples].x, samples[i * n + k + p * numSamples].x);
			}

	// shuffle y coordinates

	for (int p = 0; p < numSets; p++)
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++) {
				int k = RANDINTIN(j, n - 1);
				SWAP(samples[j * n + i + p * numSamples].y, samples[k * n + i + p * numSamples].y);
			}

}
